package week2;

//用链表实现栈


import week2.EmptyCollectionException;
import week2.StackADT;

public class LinkedStack<T> implements StackADT<T> {
    private int count;
    private LinearNode<T> top;

    public LinkedStack() {
        count = 0;
        top = null;
    }

    @Override
    public void push(T element) {
        LinearNode<T> temp = new LinearNode<T>(element);
        temp.setNext(top);
        top = temp;
        count++;
    }

    @Override
    public T pop() throws EmptyCollectionException {
        if (isEmpty())
            throw new EmptyCollectionException("Stack");

        T result = top.getElement();
        top = top.getNext();
        count--;

        return result;
    }

    @Override
    public T peek() {
        if (isEmpty())
            throw new EmptyCollectionException("Stack");
        T result = top.getElement();

        return result;
    }


    @Override
    public boolean isEmpty() {
        if (size() == 0) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public int size() {
        return count;
    }

    @Override
    public String toString() {
        LinearNode<T> temp;
        temp = top;
        String result = "";
        while (temp != null) {
            result += temp.getElement() + "\t";
            temp = temp.getNext();
        }
        return result;
    }

}